var express=require("express");
var router=express.Router();

var User=require("../models/User");
var Classify=require("../models/Classify");

/*设置统一的返回格式*/
var responseData;
router.use(function (req,res,next) {
     responseData={
         code:0,
         messages:""
     };
     next();
});
/*
*  用户注册：
*    注册逻辑：
*    
* */
/*用户注册*/
router.post("/user/register",function (req,res,next) {
   var username=req.body.userName;
   var password=req.body.password;
   var confirmpwd=req.body.confirmpwd;

  /* console.log(username)*/

    if(username==""){
       responseData.code=1;
       responseData.messages="用户名为空";
       res.json(responseData);
       return;
   }
    if(password==""){
        responseData.code=2;
        responseData.messages="密码为空";
        res.json(responseData);
        return;
    }
    if(password!=confirmpwd){
        responseData.code=3;
        responseData.messages="两次密码不一致";
        res.json(responseData);
        return;
    }

    /*验证 数据库是否存在注册的用户名*/
    User.findOne({
       userName:username
    }).then(function (info) {
       /* console.log(info);*/
        /*如果用户已注册*/
        if(info){
            responseData.code=4;
            responseData.messages="用户名已经被注册！";
            res.json(responseData);
            return;
        }
        /*如果用户没注册*/
        var user=new User({
            userName:username,
            password:password
        });
        return user.save();
    }).then(function (newInfo) {
        /* console.log(newInfo);*/
        responseData.code=200;
        responseData.messages="成功";
        res.json(responseData);

    });


});
/*用户登录*/
router.post("/user/login",function (req,res,next) {
      var loginUser=req.body.userName;
      var loginPwd=req.body.password;

      User.findOne({
          userName:loginUser
      }).then(function (info) {
          if(info){
              /*console.log(info);*/
            if(loginUser==info.userName&&loginPwd==info.password){
                  responseData.code=200;
                  responseData.messages="登录成功！";
                  responseData.userInfo={
                   _id:info._id,
                   usrName:info.userName
                  };

                  req.cookie.set("userInfo",JSON.stringify({
                      _id:info._id,
                      userName:info.userName
                  }));

                  res.json(responseData);
                  return;
            }else{
                responseData.code=78;
                responseData.messages="用户名或密码错误！";
                res.json(responseData);
                return;
            }

          }else{
              responseData.code=-1;
              responseData.messages="用户名不存在";
              res.json(responseData);
              return;
          }

      })

});

/*用户信息查看*/
router.get("/user/see",function (req,res,next) {
    var userId=req.query.id;
    User.find({_id:userId},{password:0,__v:0}).then(function (userInfo) {
        res.json(userInfo)
         // console.log(userInfo);
    })
});
/*修改（编辑用户信息）*/
router.post("/user/edit",function (req,res,next) {
    var updataUserInfo=req.body;
    var userName=updataUserInfo.userName;
    var isAdmain;
   if(updataUserInfo.isAdmain=="普通用户"){
       isAdmain=false;
   }else{
       isAdmain=true;
   }

   // var oldRole;
   /*判断要修改的用户是否是管理员 （不是可修改，是不允许修改）*/
   if(updataUserInfo.oldRole=="false"){
       /*判断修改的用户名是否存在 如果不存在可修改 存在 提示换一个试试*/
       User.find({userName:updataUserInfo.userName}).then(function (info) {
           if(info.length&&updataUserInfo.oldUserName!=updataUserInfo.userName){
               var existenceErr={
                   code:2,
                   message:"用户名已存在请换一个试试"
               };
               res.json(existenceErr);
               return;
           }else{
                var oldInfo={_id:updataUserInfo.id};
                var updataInfo={userName:updataUserInfo.userName,isAdmain:isAdmain.toString()};
                User.update(oldInfo,{$set:updataInfo}).then(function (info) {
                res.json(info);
                return;
                })
           }

       });


   }else{
       var err={code:1,message:"您没有权限修改其他管理员信息"};
        res.json(err);
   }


});

/*删除用户*/
router.get("/user/del",function (req,res,next) {
     var delInfo=req.query;
     var userRole=delInfo.userRole;


     var delObj={
         _id:delInfo.id
     };

     if(userRole=="普通用户"){
         User.remove(delObj,function (err,result) {
             if(err){
                 res.json({
                     code:2,
                     message:"用户删除失败!"
                 })
             }else{
                 res.json({
                     code:200,
                     message:"用户删除成功!"
                 })
             }

         })
     }else{
         res.json({
             code:3,
             message:"你没有权限删除其他管理员用户！"
         })
     }



});
/*用户添加*/
router.post("/user/create",function (req,res,next) {
    var userName = req.body.userName;
    var pwd = req.body.pwd;
    var tpwd = req.body.tpwd;
    var role = req.body.role;

    var isAdmin;

    if(role=="ordin"){
        isAdmin=false;
    }else if(role=="admin"){
        isAdmin=true;
    }


    /*用户名为空*/
    if(userName==""){
        responseData.code=1;
        responseData.messages="用户名为空！";
        res.json(responseData);
        return;
    }
    /*密码为空*/
    if(pwd==""){
        responseData.code=2;
        responseData.messages="密码为空！";
        res.json(responseData);
        return;
    }
    /*两次密码不一致*/
    if(pwd!=tpwd){
        responseData.code=3;
        responseData.messages="两次密码不一致！";
        res.json(responseData);
        return;
    }
    /*用户名已经存在*/
    User.find({userName:userName},{password:0,__v:0}).then(function (userInfo) {
        if(userInfo.length){
            responseData.code=4;
            responseData.messages="用户已存在,请换个用户试试！";
            res.json(responseData);
            return;
        }else{
            var addUser=new User({
                userName:userName,
                password:pwd,
                isAdmain:isAdmin
            });
            addUser.save(function (error) {
                if(!error){
                    responseData.code=200;
                    responseData.messages="用户已添加成功！";
                    res.json(responseData);
                    return;
                }else{
                    responseData.code=0;
                    responseData.messages="用户添加失败！";
                    res.json(responseData);
                    return;
                }
            })
        }
    })

});


/*分类信息查看*/
router.get("/classify/see",function (req,res,next) {
    var classifyName=req.query.classifyName;
    Classify.find({classifyName:classifyName},{__v:0},function (err,classifyInfo) {
        if(!err){
            res.json({
                code:200,
                messages:classifyInfo
            })
        }else{
            res.json({
                code:1,
                messages:"信息不存在！"
            })
        }
    })
});

/*修改（编辑分类信息）*/
router.post("/classify/edit",function (req,res,next) {
    var updataClassifyInfo=req.body;
    var needUpdata=updataClassifyInfo.oldVal;
    var finalVal=updataClassifyInfo.updataVal;

    var allClassifyInfo=[];

    Classify.find({}).then(function (allClassify) {
        var isRepeat=true;
        for(var i=0;i<allClassify.length;i++){
            allClassifyInfo.push(allClassify[i].classifyName);
        }
        for(var j=0; j<allClassifyInfo.length; j++) {
            if(allClassifyInfo[j] == needUpdata) {
                allClassifyInfo.splice(j, 1);
                break;
            }
        }
        for(var k=0;k<allClassifyInfo.length;k++){
            if(allClassifyInfo[k].toLowerCase()==finalVal.toLowerCase()){
                isRepeat=false;
            }
        }

        if(isRepeat){
            var oldInfo={classifyName:needUpdata};
            var updataInfo={classifyName:finalVal};
            Classify.update(oldInfo,{$set:updataInfo}).then(function (info) {
                if(info.n==1&&info.nModified==1&&info.ok==1){
                    res.json({
                        code:200,
                        messages:"修改成功！"
                    });
                }

                return;
            })

        }else{
            res.json({
                code:4,
                messages:"当前分类已存在！"
            })
        }




    })


   /* console.log(updataClassifyInfo)*/

});

/*删除 一个分类*/

router.get("/classify/del",function (req,res,next) {
 var delObj={
     classifyName:req.query.delVal
 };
 Classify.remove(delObj,function (err,result) {
     if(result.result.n==1&&result.result.n==1){
         res.json({
             code:200,
             messages:"删除成功！"
         })
     }else{
         res.json({
             code:01,
             messages:"删除失败！"
         })
     }

 })

 });






/*退出*/
router.get("/user/logout",function (req,res,next) {
    req.cookie.set("userInfo",null);
    res.json(responseData);
});
module.exports=router;